<?php
header("Content-type: text/plain");
$GLOBALS["access_code"] = "4124512351235"; // application must provide this number for security
$GLOBALS["host_name"] = "mysql.cba.pl";
$GLOBALS["db_name"] = "libront_cba_pl"; // name of the database
$GLOBALS["table_name"] = "wyniki"; // name of the table in the database
$GLOBALS["view_user"] = "libroncik"; // public access MySQL user
$GLOBALS["db_error"] = 0;
$GLOBALS["db_link"] = null;

//IS_ERROR
function is_error() {
	$result = ($GLOBALS["db_error"] != 0);
	return $result;
}
//ERROR
function error() {
	$GLOBALS["db_error"] = 1;
	print "Error: ".mysql_error()."\n";
}
//DO_SQL_QUERY
function sql($q) {
	$result = @mysql_query($q) or error();
	return $result;
}
//SELECT_DB
function select_db() {
	if (!mysql_select_db($GLOBALS["db_name"])) error();
}
//DB_CONNECT
function db_connect($user) {
	if ($GLOBALS["db_link"] != null) {
		@mysql_close($GLOBALS["db_link"]);
	}
	$GLOBALS["db_link"] = @mysql_connect($GLOBALS["host_name"],$user,"nowadupa1") or error();
	if (is_error()) {
		db_close();
		exit;
	}
}
//DB_CLOSE
function db_close() {
	if ($GLOBALS["db_link"] != null) {
		@mysql_close($GLOBALS["db_link"]);
	}
	print (is_error()?"0":"1");
	$GLOBALS["db_link"] = null;
}
//DB_VIEW
function db_view() {
	db_connect($GLOBALS["view_user"],$GLOBALS["view_pass"]);
	select_db();
}
//DB_STORE
function db_store($p,$r,$s,$user) {
	if ($p != "") {
		db_connect($user);
		select_db();
		sql("INSERT INTO `{$GLOBALS['table_name']}` (`Clicks`,`Left`,`Score`)  VALUES({$p},{$r},{$s})");
		db_close();
		exit;
	}
}
//DB_LIST
function db_list() {
	db_view();
	$scores = sql("SELECT `name`,`score` FROM `{$GLOBALS['table_name']}` ORDER BY `score` DESC");
	$numrows = @mysql_num_rows($scores);
	for ($j = 0;$j < $numrows;$j++) {
		$row = mysql_fetch_row($scores);
		print "{$row[0]} {$row[1]}".($j == $numrows-1?"":"\n");
	}
	@mysql_free_result($scores) or error();
	@mysql_close($GLOBALS["db_link"]) or error();
	exit;
}
//CHECK_ACCESS
function check_access() {
	if (!isset($_GET["access_code"])) {
		$GLOBALS["db_error"] = 1;
		db_close();
		exit;
	}
	if ($_GET["access_code"] != $GLOBALS["access_code"]) {
		$GLOBALS["db_error"] = 1;
		db_close();
		exit;
	}
}
//MAIN
if (isset($_GET["action"])) {
	check_access();
	if ($_GET["action"] == "submit" && isset($_GET["admin_user"]) && isset($_GET["clicks"]) && isset($_GET["left"]) && isset($_GET["score"])) {
		db_store($_GET["clicks"],$_GET["left"],$_GET["score"],$_GET["admin_user"]);
	}
	else if ($_GET["action"] == "list") {
		db_list();
	}
}
?>